//
//  ContentViewController.m
//  huanxin
//
//  Created by 郭亚 on 16/4/28.
//  Copyright © 2016年 郭亚. All rights reserved.
//

#import "ContentViewController.h"

#import <EaseMob.h>

#import <UIView+KeyboardObserver.h>


@interface ContentViewController ()<UITableViewDataSource, UITableViewDelegate, EMChatManagerDelegate>

@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong) EMConversation *conversation;

@property (nonatomic, strong) UITextField *textField;

@property (nonatomic, strong) UIView *toolView;

@end

@implementation ContentViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.tabBarController.tabBar.hidden = YES;
    [self createView];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:(UIBarButtonSystemItemAdd) target:self action:@selector(sendMessage)];
    
    [[EaseMob sharedInstance].chatManager addDelegate:self delegateQueue:dispatch_get_main_queue()];
    [self reloadMessage];
}

- (void)createView
{
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height / 5 * 4) style:(UITableViewStylePlain)];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [self.view addSubview:_tableView];
    
    _toolView = [[UIView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(_tableView.frame), self.view.frame.size.width, self.view.frame.size.height / 5)];
    [self.view addSubview:_toolView];
    
    _textField = [[UITextField alloc] initWithFrame:CGRectMake(10, 5, self.view.frame.size.width - 20, self.view.frame.size.height / 5 - 10)];
    _textField.layer.cornerRadius = 10;
    _textField.layer.borderColor = [UIColor orangeColor].CGColor;
    _textField.layer.borderWidth = 2;
    [self.toolView addSubview:_textField];
}



- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _conversation.loadAllMessages.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

    static NSString *string = @"CELL";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:string];
    
    if(!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:string];
    }
    
    // 每一个message表示一条聊天记录
    EMMessage *message = self.conversation.loadAllMessages[indexPath.row];
    // EMTextMessageBody 表示聊天的信息
    EMTextMessageBody *body = [message.messageBodies lastObject];
    // message.to 表示聊天的对象
    if ([message.to isEqualToString:self.chatter]) {
        cell.textLabel.text = @"";
        cell.detailTextLabel.text = body.text;
    } else {
        cell.textLabel.text = body.text;
        cell.detailTextLabel.text = @"";
    }
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self.view endEditing:NO];
}

- (void)reloadMessage
{
    self.conversation = [[EaseMob sharedInstance].chatManager conversationForChatter:self.chatter conversationType:eConversationTypeChat];
    [self.tableView reloadData];
    
    if (self.conversation.loadAllMessages.count != 0) {
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:self.conversation.loadAllMessages.count - 1 inSection:0];
        
        [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];
    }
}

- (void)didReceiveMessage:(EMMessage *)Message
{
    [self reloadMessage];
}
- (void)sendMessage
{
    // 聊天的文本对象类型
    EMChatText *text = [[EMChatText alloc] initWithText:self.textField.text];
//    EMChatText *text = [[EMChatText alloc] initWithText:@"敢不敢看看崩溃信息"];
    // 聊天的文本消息体对象
    EMTextMessageBody *textMessageBody = [[EMTextMessageBody alloc] initWithChatObject:text];
    // 聊天消息类
    EMMessage *message = [[EMMessage alloc] initWithReceiver:self.chatter bodies:@[textMessageBody]];
    
    [[EaseMob sharedInstance].chatManager asyncSendMessage:message progress:nil prepare:^(EMMessage *message, EMError *error) {
        // 准备发送
    } onQueue:dispatch_get_main_queue() completion:^(EMMessage *message, EMError *error) {
        // 发送成功
        if (!error) {
            self.textField.text = nil;
            [self.view endEditing:NO];
            [self reloadMessage];
        }
    } onQueue:dispatch_get_main_queue()];
}

- (void)viewDidAppear:(BOOL)animated
{
#warning mark 改了
//    [super viewDidAppear:animated];
    
    _tableView.contentSize = CGSizeMake(0, _tableView.frame.size.height);
    [_tableView addKeyboardObserver];
    [_toolView addKeyboardObserver];
}

- (void)viewWillDisappear:(BOOL)animated
{
    self.tabBarController.tabBar.hidden = NO;

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
